import os
import platform
from pathlib import Path
import subprocess
import threading
import time
from queue import Queue
import pygame


class AudioPlayer:
    def __init__(self, callback=None):
        self.callback = callback
        self._is_playing = False
        self._stop_event = threading.Event()
        self._play_thread = None
        self._sound_queue = Queue()
        self._current_sound = None
        self._volume_interface = None

        # 初始化 pygame mixer
        try:
            pygame.mixer.init()
        except Exception as e:
            print(f"初始化音频系统失败: {str(e)}")
            if self.callback:
                self.callback(f"初始化音频系统失败: {str(e)}")

        self.sound_name = 'notification.mp3'  # 默认音频文件名

        # 设置音频文件目录
        self.sounds_dir = Path(__file__).parent.parent / 'resources' / 'sounds'
        self.sounds_dir.mkdir(parents=True, exist_ok=True)

    @property
    def is_playing(self):
        """获取当前播放状态"""
        return self._is_playing

    def get_system_volume(self):
        """获取系统音量"""
        try:
            system = platform.system()
            if system == 'Darwin':  # macOS
                cmd = 'osascript -e "output volume of (get volume settings)"'
                result = subprocess.check_output(
                    cmd, shell=True).decode().strip()
                return int(result)
            elif system == 'Windows':
                # 使用 pygame 的音量控制
                return int(pygame.mixer.music.get_volume() * 100)
            elif system == 'Linux':
                cmd = "amixer get Master | grep -o '[0-9]*%' | head -1 | tr -d '%'"
                result = subprocess.check_output(
                    cmd, shell=True).decode().strip()
                return int(result)
        except Exception as e:
            print(f"获取系统音量失败: {str(e)}")
            if self.callback:
                self.callback(f"获取系统音量失败: {str(e)}")
            return None

    def is_system_muted(self):
        """检查系统是否静音"""
        try:
            if platform.system() == 'Windows':
                return pygame.mixer.music.get_volume() == 0
            else:
                volume = self.get_system_volume()
                return volume is not None and volume == 0
        except Exception as e:
            print(f"检查系统音量失败: {str(e)}")
            if self.callback:
                self.callback(f"检查系统音量失败: {str(e)}")
            return False

    def play_sound(self):
        """播放指定的音频文件"""
        if self._is_playing:
            return False

        sound_path = self.sounds_dir / self.sound_name
        if not sound_path.exists():
            raise FileNotFoundError(f"音频文件不存在: {sound_path}")

        # 检查系统音量
        if self.is_system_muted():
            return "MUTED"

        self._current_sound = str(sound_path)
        self._stop_event.clear()
        self._is_playing = True

        # 在新线程中播放音频
        self._play_thread = threading.Thread(target=self._play_audio)
        self._play_thread.daemon = True
        self._play_thread.start()

        return True

    def stop_sound(self):
        """停止当前播放的音频"""
        if self._is_playing:
            self._stop_event.set()
            pygame.mixer.music.stop()
            if self._play_thread:
                self._play_thread.join()
            self._is_playing = False
            self._current_sound = None
            return True
        return False

    def _play_audio(self):
        """内部方法：实际播放音频的处理"""
        try:
            # 使用 pygame 播放音频
            pygame.mixer.music.load(self._current_sound)
            pygame.mixer.music.play()

            # 等待播放完成或被停止
            while pygame.mixer.music.get_busy() and not self._stop_event.is_set():
                time.sleep(0.1)

            # 确保停止播放
            pygame.mixer.music.stop()

            # 播放完成后重置状态
            if not self._stop_event.is_set():
                self._is_playing = False
                self._current_sound = None
        except Exception as e:
            print(f"播放音频时发生错误: {str(e)}")
            if self.callback:
                self.callback(f"播放音频时发生错误: {str(e)}")

            self._is_playing = False
            self._current_sound = None
